from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.forms import ModelForm
from django.shortcuts import render, redirect
from django import forms
from django.utils.safestring import mark_safe

from app01 import models
from app01.models import Department
from app01.utils.pagination import Pagination
from app01.utils.bootstrap import BootstrapModelForm


def depart_list(request):
    """部门列表"""

    depart_list = Department.objects.all()

    return render(request, "depart_list.html", {"depart_list": depart_list})


def depart_add(request):
    """部门添加"""
    if request.method == "GET":
        return render(request, "depart_add.html")

    # 获取用户提交的部门数据
    depart_title = request.POST.get("depart_title")

    # 保存到数据库
    models.Department.objects.create(title=depart_title)

    return redirect("/depart/list/")


def depart_del(request):
    """部门删除"""
    # 获取部门id
    depart_id = request.GET.get("depart_id ")

    # 根据部门id删除部门
    models.Department.objects.filter(id=depart_id).delete()

    return redirect("/depart/list/")


def depart_edit(request, id):
    """部门编辑"""
    if request.method == "GET":
        # 获取部门id
        row_object = models.Department.objects.filter(id=id).first()

        return render(request, "depart_edit.html", {"row_object": row_object})
    title = request.POST.get("depart_title")
    models.Department.objects.filter(id=id).update(title=title)
    return redirect("/depart/list")


from django.shortcuts import render, redirect, HttpResponse
from openpyxl import load_workbook


def depart_multi(request):
    """ 文件上传(Excel) """

    # 获取上传的 Excel 文件对象
    file_object = request.FILES.get('exc')
    print(file_object)

    # 打开 Excel 文件读取内容
    wb = load_workbook(file_object)
    sheet = wb.worksheets[0]

    # 循环获取每一行数据,并更新至数据库
    for row in sheet.iter_rows(min_row=2):
        exc_title = row[0].value
        # 如果表格中的数据在数据库中不存在,则进行创建
        if not Department.objects.filter(title=exc_title).exists():
            Department.objects.create(title=exc_title)

    return HttpResponse("上传成功")
